import React, { PureComponent } from "react";
import { connect } from "dva";
import style from "styled-components";
import moment from "moment";
import {
  Input,
  Button,
  message,
  DatePicker,
  Checkbox,
  Form,
  Modal,
  TreeSelect
} from "antd";
import Drawer from "react-motion-drawer";
import PSelect from "../../../components/Pro/PSelect";
import {
  updateComSecurityPpenalty,
  getComSecurityPenaltyById,
  getTreeperBydepart
} from "../../../services/api";

const FormItem = Form.Item;
const dateFormat = "YYYY/MM/DD";
const { TextArea } = Input;
const config = {
  rules: [
    {
      type: "object",
      required: false,
      message: "请选择日期!"
    }
  ]
};
message.config({
  top: 100,
  right: 5,
  duration: 2,
});

@connect(state => ({ profile: state.profile }))
@Form.create()
export default class EditPunishment extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      openEdit: this.props.openEdit,
      penaltyId: 0,
      treeData: [
        //树
        //{ title: "", key: "" }
      ],
      showPerId: 0,
      perIdArray:[],
      comSecurityPenalty: {
        penaltyDate: "",
        penaltyType: "",
        penaltyUnit: "",
        isCrime: false,
        penaltyContent: "",
        penaltyReason: "",
        remark: ""
      }
    };
  }

  /******************************生命周期******************************/

  componentWillReceiveProps(nextProps) {
    this.setState({ openEdit: nextProps.visible });
    if (nextProps.penaltyId !== this.state.penaltyId) {
      if (nextProps.penaltyId === 0 || nextProps.penaltyId === undefined) {
        return;
      }
      this.setState({
        penaltyId: nextProps.penaltyId
      });
      this.renderDate(nextProps.penaltyId);
    }
  }
  componentDidMount() {
    getTreeperBydepart({}).then(
      response => {
        console.log(response, "getTreeperBydepart-response");
        this.setState({ treeData: response.data});
      },
      err => {
        console.log(err, "getTreeperBydepart-err");
      }
    );
  }
  //树形选择器改编
  handleTreeSelectChange = (value, label, extra) => {
    const lastValue = this.state.perIdArray;
    if(extra.triggerNode && extra.triggerNode.props && extra.triggerNode.props.treeType === "1"){
    console.log("部门");
      this.setState({perIdArray:lastValue});
    }else{
    this.setState({perIdArray:value}); }
  }
  renderDate = (pro) => {
    console.log('id的值', pro);
    getComSecurityPenaltyById({ penaltyId: pro }).then((data) => {
      console.log('shuju', data.data);
      console.log("comSecurityPenalty", data.data.comSecurityPenalty);
      if (data.data) {
        if (data.data.comSecurityPenalty.isCrime === "1") {
          data.data.comSecurityPenalty.isCrime = true;
          console.log(
            "获取单个处罚信息-checkbox",
            data.data.comSecurityPenalty.isCrime
          );
        } else {
          data.data.comSecurityPenalty.isCrime = false;
          console.log(
            "获取单个处罚信息-checkbox",
            data.data.comSecurityPenalty.isCrime
          );
        }
      }
      const { setFieldsValue } = this.props.form;
      //人员处理
      const perIdArray = [];
      data.data.perList && data.data.perList.map((item)=>{
      const { perId } = item;
      perIdArray.push(perId.toString());
      });
      console.log(perIdArray);
      setFieldsValue({
        penaltyDate: data.data.comSecurityPenalty.penaltyDate || '',
        penaltyType: data.data.comSecurityPenalty.penaltyType || '',
        penaltyUnit: data.data.comSecurityPenalty.penaltyUnit || '',
        isCrime: data.data.comSecurityPenalty.isCrime || '',
        penaltyContent: data.data.comSecurityPenalty.penaltyContent || '',
        penaltyReason: data.data.comSecurityPenalty.penaltyReason || '',
        remark: data.data.comSecurityPenalty.remark || '',
      });
      this.setState({
        perIdArray,
        comSecurityPenalty: {
          penaltyDate: data.data.comSecurityPenalty.penaltyDate || '',
          penaltyType: data.data.comSecurityPenalty.penaltyType || '',
          penaltyUnit: data.data.comSecurityPenalty.penaltyUnit || '',
          isCrime: data.data.comSecurityPenalty.isCrime || '',
          penaltyContent: data.data.comSecurityPenalty.penaltyContent || '',
          penaltyReason: data.data.comSecurityPenalty.penaltyReason || '',
          remark: data.data.comSecurityPenalty.remark || '',
        },
      });
    }, (err) => {
      console.log(err);
    });
  }

  //表单提交
  handlePunishmentSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.penaltyId = this.state.penaltyId;
        values.perIdString=this.state.perIdArray;
        const rangeValue = values["penaltyDateSd"];
        values.penaltyDate = rangeValue.format("YYYY-MM-DD");
        const { isCrime } = values;
        if (isCrime) {
          values.isCrime = "1";
        } else {
          values.isCrime = "0";
        }
        console.log('修改表单提交内容');
        console.log(values);
        updateComSecurityPpenalty(values).then(
          data => {
            console.log(data);

            this.setState({ openEdit: false });
            this.props.tableUpdate();
          },
          err1 => {
            console.log(err1);
          }
        );
      }
    });
  };

  hideModal = () => {
    this.setState({
      visible: true,
    });
  }

  handleModalOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
      openEdit: false,
    });
  }

  handleModalCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 17
        },
        md: {
          span: 17
        }
      }
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <Content>
        {/*处罚详情*/}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.openEdit}
          noTouchClose
          width={600}
          zIndex={2}
          className="drawer-box"
          onChange={openEdit => {
            this.props.onChange(openEdit);
            this.setState({ openEdit });
          }}
        >
          <div className="drawer">
            <div className="drawer-header">处罚详情</div>
            <div className="drawer-content">
              <Form
                style={{ marginTop: 24 }}
                onSubmit={this.handlePunishmentSubmit}
              >
                  {this.state.showPerId === 1 ?//看看是否没选择人员
                    <Formitem style={{ marginLeft: 50,marginBottom:0, 'display': 'inline-block' }}>
                    <Formlable >
                    <span style={{ color: '#f5222d' }}>* </span>&nbsp;被处罚人员:</Formlable>
                    <TreeSelect
                    value={this.state.perIdArray}
                    style={{
                        width: 294,
                        border: '1px solid #f5222d',
                        borderRadius: 4
                    }}
                    dropdownStyle={{
                        maxHeight: 400,
                        overflow: "auto"
                    }}
                    treeData={this.state.treeData}
                    onChange={this.handleTreeSelectChange}
                    treeDefaultExpandAll
                    multiple
                    /> 
                    <div style={{ 'color': '#f5222d', marginLeft: 114 }}> 请选择奖励人员</div>
                    </Formitem>
                    :
                    <Formitem style={{ marginLeft: 50,marginBottom:24, 'display': 'inline-block' }}>
                    <Formlable >
                    <span style={{ color: '#f5222d' }}>* </span>&nbsp;被表彰奖励人员:</Formlable>
                    <TreeSelect
                    value={this.state.perIdArray}
                    style={{
                        width: 294,
                    }}
                    dropdownStyle={{
                        maxHeight: 400,
                        overflow: "auto"
                    }}
                    treeData={this.state.treeData}
                    onChange={this.handleTreeSelectChange}
                    treeDefaultExpandAll
                    multiple
                    /> 
                    <div/>
                    </Formitem>} 
                <FormItem {...formItemLayout} label="处罚日期">
                  {getFieldDecorator(
                    "penaltyDateSd",
                    {
                      initialValue: moment(
                        this.state.comSecurityPenalty.penaltyDate,
                        dateFormat
                      ),
                      rules: [
                        {
                          required: true, message: '请选择处罚日期'
                        }
                      ]
                    },
                    config
                  )(<DatePicker style={{ width: 294 }} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="处罚类型">
                  {getFieldDecorator("penaltyType", {
                    initialValue: this.state.comSecurityPenalty.penaltyType,
                    rules: [
                      {
                        required: true, message: '请选择处罚类型'
                      }
                    ]
                  })(
                    <PSelect type="penaltyType" style={{ width: 294 }}  />)}
                </FormItem>
                <FormItem {...formItemLayout} label="做出处罚单位">
                  {getFieldDecorator("penaltyUnit", {
                    initialValue: this.state.comSecurityPenalty.penaltyUnit,
                    rules: [
                      {
                        required: true, message: '请填写做出处罚单位'
                      }
                    ]
                  })(
                    <Input
                      maxLength="50"
                      style={{ width: 294 }}
                      placeholder="请输入"
                    />
                    )}
                </FormItem>

                <FormItem {...formItemLayout} label="追究刑事责任">
                  {getFieldDecorator("isCrime", {
                    valuePropName: "checked",
                    initialValue: this.state.comSecurityPenalty.isCrime
                  })(<Checkbox style={{ width: 294 }} />)}
                </FormItem>

                <FormItem {...formItemLayout} label="处罚内容">
                  {getFieldDecorator("penaltyContent", {
                    initialValue: this.state.comSecurityPenalty.penaltyContent,
                    rules: [
                      {
                        required: true, message: '请填写处罚内容'
                      }
                    ]
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength="500"
                      rows={4}
                      placeholder="请输入"
                    />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="处罚原因">
                  {getFieldDecorator("penaltyReason", {
                    initialValue: this.state.comSecurityPenalty.penaltyReason,
                    rules: [
                      {
                        required: true, message: '请填写处罚原因'
                      }
                    ]
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      maxLength="500"
                      rows={4}
                      placeholder="请输入"
                    />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="备注">
                  {getFieldDecorator("remark", {
                    initialValue: this.state.comSecurityPenalty.remark
                  })(
                    <TextArea
                      style={{ width: 294 }}
                      rows={4}
                      placeholder="请输入"
                    />
                    )}
                </FormItem>
              </Form>
            </div>
            <div className="drawer-footer">
              <Button onClick={this.hideModal}>返回</Button>
              <Button type="primary" onClick={this.handlePunishmentSubmit}>
                提交
              </Button>
            </div>
          </div>
        </Drawer>
        <Modal
          title="提示"
          visible={this.state.visible}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}
        >
          <p>返回会取消您已填写的内容，确定返回？</p>
        </Modal>
      </Content>
    );
  }
}

/************************样式************************/

const Content = style.div`{
      font-size: 14px;
      color: rgba(0,0,0,0.65);
      .searchpanel{
         margin-bottom:16px;
        .post{
          margin:0 8px 0 16px;
        }
      }
      .btns{
        margin-top:16px;
      }
    }`;
    const Formitem=style.label`{

      font-family: "Monospaced Number", "Chinese Quote", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
      font-size: 14px;
      line-height: 1.5;
      color: rgba(0, 0, 0, 0.65);
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      list-style: none;
      margin-bottom: 24px;
      vertical-align: top;
      -webkit-transition: margin 0.15s steps(1);
      transition: margin 0.15s steps(1);
    }`;
    const Formlable=style.span`{
      text-align: right;
      vertical-align: middle;
      line-height: 39.9999px;
      display: inline-block;
      overflow: hidden;
      white-space: nowrap;
      margin-right:8px;
    }`;
  
  

